﻿using Blog.Model;
using Blog.Utility.ApiResult;
using IBaseService;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Blog.Controllers
{
	[Route("api/[controller]")]
	[ApiController]
	[Authorize]
	public class RoleController : ControllerBase
	{
		private readonly IRoleService _roleService;

		public RoleController(IRoleService roleService)
		{
			_roleService = roleService;
		}

		[HttpGet("RoleList")]
		public async Task<ActionResult<ApiResult>> QueryList()
		{
			var list = await _roleService.QueryAsync();
			return ApiResultTool.Success(list);
		}

		[HttpPost("CreateRole")]
		public async Task<ActionResult<ApiResult>> CreateArticle(string roleName)
		{
			Role role = new Role()
			{
				RoleName = roleName,
				IsDel = 0
			};

			bool res = await _roleService.CreateAsync(role);
			if (!res) return ApiResultTool.Fail("新增角色失败，请联系系统管理员");
			return ApiResultTool.Success(role);
		}

		[HttpPost("DeleteRole")]
		public async Task<ActionResult<ApiResult>> DeleteArticle(int id)
		{
			bool res = await _roleService.DeleteByIdAsync(id);
			if (!res) return ApiResultTool.Fail("删除角色失败");
			return ApiResultTool.Success(res);
		}

		[HttpPost("UpdateRole")]
		public async Task<ActionResult<ApiResult>> UpdateArticle(int id, string roleName)
		{
			Role role = await _roleService.FindByIdAsync(id);
			if (role == null) return ApiResultTool.Fail("没有找到该角色");
			role.RoleName = roleName;

			bool res = await _roleService.EditAsync(role);
			if (!res) return ApiResultTool.Fail("修改角色失败");
			return ApiResultTool.Success(res);
		}
	}
}
